import config from './config.js';
import request from '../api/request.js'
import stroe from '@/store/index.js'

// 图片上传
function uploadFile(url, file) {
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: config.baseUrl + url,
			filePath: file,
			name: 'file',
			dataType: "json",
			success: function(uploadFileRes) {
				if (uploadFileRes.data) {
					var type = typeof uploadFileRes.data;
					if (type == 'string') {
						uploadFileRes.data = JSON.parse(uploadFileRes.data)
					}
					resolve(uploadFileRes.data);
				}
			},
			fail: function(res) {
				console.log(res)
			},
			complete: function() {
				
			}
		})
	})
}

// 图片上传2
function uploadFiles(file) {
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: config.baseUrl + `/zzjApp/uploade?bid=${stroe.state.bid}`,
			filePath: file,
			name: 'file',
			dataType: "json",
			success: function(uploadFileRes) {
				if (uploadFileRes.data) {
					 if(typeof uploadFileRes.data != 'object'){
						  uploadFileRes.data = JSON.parse(uploadFileRes.data)
					 }
					resolve(uploadFileRes.data);
				}
				
			},
			fail: function(res) {
				console.log(res)
			},
			complete: function() {

			}
		})
	})
}

async function chooseImage(count){
	return new Promise((resolve,reject)=>{
		 uni.chooseImage ({
			count,
			success:async (res)=>  {
				const tempFilePaths = res.tempFilePaths;
				let arr = [];
				for(const item of tempFilePaths){
					let result = await uploadFiles(item);
					let imgItem = result.url.substring(22,result.url.length);
					arr.push(imgItem)
				}
				resolve(arr);
			}
		})
	})
}

// import HTMLParser from "./html-parser.js"
function richTxt(html) {
	var capture = html,
		array = [];
	var i = -1;
	if (html) {
		html = capture.replace(/src=\s*['"]([^'"]+)[^>]*>/gi, function(match, capture) {
			i++;
			if (capture.indexOf('http') > -1) {
				array.push(capture);
				capture = ' src="' + capture +
					'" style="max-width: 100%; height: auto; margin: 0 auto; display: block;" data-index=' + i + ' />';
				return capture
			} else {
				array.push(config.imgUrl + capture);
				capture = ' src="' + config.imgUrl + capture +
					'" style="max-width: 100%; height: auto; margin: 0 auto; display: block;" data-index=' + i + ' />';
				return capture
			}
		})
		.replace(/<section/g, '<div').replace(/\/section>/g, '/div>')
		.replace(/<o:p>/g, '').replace(/<\/o:p>/g, '')
		.replace(/<font/g, '<span').replace(/\/font>/g, '/span>')
		.replace(/<table/g, '<table style="max-width:100%;"')
		// html = new HTMLParser(html.trim());
	}
	var obj = {
		html: html,
		imgs: array
	};
	return obj;
}

function call() {
	let phone = uni.getStorageSync('startUp').service_tel;
	if (phone) {
		uni.makePhoneCall({
			phoneNumber: phone
		})
	} else {
		uni.showToast({
			title: "很抱歉，暂未配置联系电话！",
			icon: 'none'
		})
	}
}

function Tel(phone) {
	
	if (phone) {
		uni.makePhoneCall({
			phoneNumber: phone
		})
	} else {
		uni.showToast({
			title: "很抱歉，暂未配置联系电话！",
			icon: 'none'
		})
	}
}

function toUrl(url) {
	uni.navigateTo({
		url: url
	})
}

function rectTo(url) {
	uni.redirectTo({
		url: url
	})
}

function back(time){
	uni.navigateBack({
		delta: time?time:1
	})
}

function toGoods(goods_id,store_id) {
	if(store_id){
		uni.navigateTo({
			url:`/pages/goods/goods_detail?goodsid=${goods_id}&shop_id=${store_id}`
		})
	}else{
		uni.navigateTo({
			url: '/pages/goods/goods_detail?goodsid=' + goods_id
		})
	}
}


function istoGoods(type,goods_id,lesson_id) {
	console.log(111);
	if(type == 13){
		uni.navigateTo({
			url: '/pages/ply/courseDetail?lid=' + lesson_id
		})
	}else{
		uni.navigateTo({
			url: '/pages/goods/goods_detail?goodsid=' + goods_id
		})
	}
	
}

function backHome() {
	stroe.commit('changeTab',{tabId:1});
	uni.redirectTo({
		url: `/pages/index/index`
	})

}


function timeFormat(number, format) {
	/** 
	 * 时间戳转化为年 月 日 时 分 秒 
	 * number: 传入时间戳 
	 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
	 */
	function formatTime(number, format) {
		var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
		var returnArr = [];
		var date = new Date(number * 1000);
		returnArr.push(date.getFullYear());
		returnArr.push(formatNumber(date.getMonth() + 1));
		returnArr.push(formatNumber(date.getDate()));

		returnArr.push(formatNumber(date.getHours()));
		returnArr.push(formatNumber(date.getMinutes()));
		returnArr.push(formatNumber(date.getSeconds()));

		for (var i in returnArr) {
			format = format.replace(formateArr[i], returnArr[i]);
		}
		return format;
	}

	//数据转化  
	function formatNumber(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}
	return formatTime(number, format);
}

// 图片预览
function previewImage(i, imgArry) {
	if (imgArry) {
		let arr = [];
		for (let i in imgArry) {
			arr.push(config.imgUrl + imgArry[i].img)
		}
		uni.previewImage({
			current: i,
			urls: arr,
			indicator: "number",
			loop: true
		})
	}
}

function previewImgs(i, imgArry) {
	if (imgArry) {
		let arr = [];
		for (let i in imgArry) {
			arr.push(config.imgUrl + imgArry[i])
		}
		uni.previewImage({
			current: i,
			urls: arr,
			indicator: "number",
			loop: true
		})
	}
}

// H5禁止分享等动作
function H5HideShare() {
	function onBridgeReady() {
	    WeixinJSBridge.call('hideOptionMenu');
		WeixinJSBridge.call('hideToolbar');
	}
	if (typeof WeixinJSBridge == "undefined") {
	    if (document.addEventListener) {
	        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
	    } else if (document.attachEvent) {
	        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
	        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
	    }
	} else {
	    onBridgeReady();
	}
}

function strlen(str){
	var len = 0;
	for (var i=0; i<str.length; i++) {
		var c = str.charCodeAt(i);
		//单字节加1
		if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
			len++;
		}else {
			len+=2;
		}
	}
	return len;
}
function BarTitle(title){
	uni.setNavigationBarTitle({
		title
	})
}

export default {
	richTxt,
	uploadFile,
	uploadFiles,
	chooseImage,
	call,
	Tel,
	backHome,
	toUrl,
	rectTo,
	previewImage,
	previewImgs,
	timeFormat,
	H5HideShare,
	toGoods,
	istoGoods,
	back,
	strlen,
	BarTitle
}
